package sz.szsmk.citizencard.util;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.util.Hashtable;

import static android.graphics.Color.BLACK;

/**
 * Created by chensf on 17/9/29.
 */

public class QrCodeUtils {


    public static Bitmap createQRCode(String str, int widthAndHeight)
            throws WriterException {
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix matrix = new MultiFormatWriter().encode(str,
                BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);

        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];
        //画黑点
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = BLACK; //0xff000000
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
//        if (logo != null) {
//            bitmap = addLogo(bitmap, logo);
//        }
        return bitmap;
    }


    //    /**
//     * 在二维码中间添加Logo图案
//     */
    private static Bitmap addLogo(Bitmap src, Bitmap logo) {
        if (src == null) {
            return null;
        }

        if (logo == null) {
            return src;
        }

        //获取图片的宽高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }

        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }

        //logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);

            canvas.save();
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }


    /**
     * 生成包含logo的二维码 （logo尺寸尽量越小越好，超过二维码尺寸的1/8就会覆盖二维码而难以识别）
     * 代码对尺寸做了处理，如果超出1/6则按二维码尺寸的1/6展示logo
     *
     * @param bitmap     logo图片
     * @param message    二维码内容
     * @param sizeOfCode 生成二维码尺寸
     * @param sizeOfLogo 显示logo尺寸
     * @return
     * @throws Exception
     */
    public static Bitmap createQRCode(Bitmap bitmap, String message,
                                      int sizeOfCode, int sizeOfLogo) throws Exception {

        return createQRCode(bitmap, message, sizeOfCode, sizeOfLogo, BLACK);

    }

    private static Bitmap createQRCode(Bitmap bitmap, String message,
                                       int sizeOfCode, int sizeOfLogo, int color) throws Exception {
        if (bitmap == null || sizeOfLogo <= 0) {
            return createQRCode(message, sizeOfCode);
        }

        if (null == message || message.length() <= 0) {
            throw new NullPointerException("QRCode message is not null");
        }

        if (sizeOfCode <= sizeOfLogo) {
            throw new Exception("QRCode size is smaller than the logo size");
        }
        if (sizeOfCode / sizeOfLogo <= 6) {
            sizeOfLogo = sizeOfCode / 7;
        }

        Bitmap logoBitmap = scaleBitmap(bitmap, sizeOfLogo);// logo缩放
        final int LOGO_HALFWIDTH = sizeOfLogo / 2;
        // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
        MultiFormatWriter formatWriter = new MultiFormatWriter();
        BitMatrix matrix = formatWriter.encode(message, BarcodeFormat.QR_CODE,
                sizeOfCode, sizeOfCode);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // 二维矩阵转为一维像素数组,也就是一直横着排了
        int halfW = width / 2;
        int halfH = height / 2;
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (x > halfW - LOGO_HALFWIDTH && x < halfW + LOGO_HALFWIDTH
                        && y > halfH - LOGO_HALFWIDTH
                        && y < halfH + LOGO_HALFWIDTH) {
                    pixels[y * width + x] = logoBitmap.getPixel(x - halfW
                            + LOGO_HALFWIDTH, y - halfH + LOGO_HALFWIDTH);
                } else {
                    if (matrix.get(x, y)) {
                        pixels[y * width + x] = color;
                    }
                }
            }
        }
        Bitmap codeBitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        // 通过像素数组生成bitmap
        codeBitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return codeBitmap;
    }

    /**
     * bitmap 缩放处理
     *
     * @param bitmap
     * @param size
     * @return
     */
    private static Bitmap scaleBitmap(Bitmap bitmap, int size) {
        if (bitmap == null) {
            return null;
        }
        Matrix m = new Matrix();
        float sx = (float) size / bitmap.getWidth();
        float sy = (float) size / bitmap.getHeight();
        m.setScale(sx, sy);
        Bitmap scaleBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), m, false);
        /*if (bitmap != null) {
            bitmap.recycle();
			bitmap = null;
		}*/
        return scaleBitmap;

    }

}
